import { createAlova, type Alova, type AlovaGenerics, type RespondedHandlerRecord } from 'alova';
import { useUserstore } from '@/store/modules/user';
import { mockAdapter } from '@/api/mock/adapter';
// import { pingAndCompare } from './ping';
import { onDestroy } from 'svelte';
import { get } from 'svelte/store';

// const ApiUrlCN = import.meta.env.VITE_BASE_API_URL_CN;

export const base = {
	/** 真实请求的路径前缀 */
	ApiUrl: import.meta.env.VITE_BASE_API_URL,
	webType: import.meta.env.VITE_WEB_TYPE
};

// await (async () => {
// 	if (import.meta.env.VITE_ENV !== 'production') return;
// 	const url = await pingAndCompare([base.ApiUrl, ApiUrlCN]);

// 	if (url) {
// 		const prefix = import.meta.env.VITE_URL_PREFIX;
// 		base.ApiUrl = url + prefix;
// 	}
// })();

// console.log(baseApiUrl);

// alova 中的钩子自带请求取消，不需要像axios那样手动取消请求
// const controller = new AbortController();

const clearUserState = () => {
	const userStore = useUserstore();
	userStore.clearLoginState();
};

const _401_resolve = (res) => {
	if (res.code === 401) clearUserState();
};

/** 使用 responded 对象分别指定请求成功的拦截器和请求失败的拦截器 */
const responded: RespondedHandlerRecord<AlovaGenerics> = {
	/**
	 * @param response 参数接收Response对象
	 * @param method 当前请求的method实例，你可以用它同步请求前后的配置信息
	 * @returns Response
	 */
	onSuccess: async (response /** _method */) => {
		// console.log('请求成功, response:', response);
		if (response.status >= 200 && response.status < 300) {
			const result = await response.json();
			_401_resolve(result);
			if (result.body) return result.body;
			return result;
		}

		if (response.status === 401) clearUserState();

		if (response.status === 403) {
			// 没有权限
			const data = await response.json();
			throw new Error(data.message);
		}

		if (response.status === 404) {
			// 请求资源不存在
			const resp = { message: '请求资源不存在', ok: false, code: 404 };
			return resp;
		}

		if (response.status === 500) {
			// 服务器错误
			const resp = { message: '服务器错误', ok: false, code: 500 };
			return resp;
		}

		// 请求失败
		if (response.status >= 400) {
			const data = await response.json();
			throw new Error(data.message);
		}

		return await response.json();
	},
	onError: (err) => {
		if (err.message.includes('network timeout')) {
			return { message: 'TIME OUT', ok: false, code: 504 };
		}
		return err;
	},
	// 请求完成的拦截器
	// 当你需要在请求不论是成功、失败、还是命中缓存都需要执行的逻辑时，可以在创建alova实例时指定全局的`onComplete`拦截器，例如关闭请求 loading 状态。
	// 接收当前请求的method实例
	onComplete: async (/* method */) => {
		// 处理请求完成逻辑
		// if (method.config) return;
	}
};

const cacheFor = {
	GET: 10 * 1000, // 设置所有Get缓存20分钟关闭所有GET缓存
	POST: 0 // 关闭所有POST缓存
};

const service: Alova<AlovaGenerics> = createAlova({
	baseURL: base.ApiUrl,
	timeout: 20000,
	responded,
	cacheFor,
	beforeRequest: (method) => {
		const userStore = useUserstore();
		if (get(userStore.token)) {
			method.config.headers.Authorization = 'Bearer ' + get(userStore.token);
		}

		method.config.params['webType'] = base.webType;
	},
	// requestAdapter: adapterFetch()
	requestAdapter: mockAdapter
});

export function abort_req(destory: boolean = true) {
	const controller = new AbortController();

	if (destory) onDestroy(() => controller.abort());
	return { abort: controller.abort, signal: controller.signal };
}

export default service;

export { service as alova };
